<!--
 * @Author: ZhaoZhiqi
 * @Date: 2022-10-19 11:08:20
 * @LastEditors: ZhaoZhiqi
 * @LastEditTime: 2023-01-10 14:38:56
 * @Description: 群众帮代办
 * @FilePath: \tuanfeng-mini\src\pages\masses.vue
-->
<template>
    <div class="container">
        <u-form :model="form" ref="uForm" label-width="90px">
            <div class="item">
                <u-form-item label="代办事项" prop="title" :label-style="{color: '#0c3b96'}">
                    <span>{{form.title}}</span>
                </u-form-item>
            </div>
            <div class="item">
                <u-form-item label="联系电话" prop="phone" required :label-style="{color: '#0c3b96'}">
                    <u-input type="number" :maxlength="11" v-model="form.phone" placeholder="请输入您的手机号" />
                </u-form-item>
            </div>
            <div class="item">
                <u-form-item label="姓名" prop="name" required :label-style="{color: '#0c3b96'}">
                    <u-input v-model="form.name" placeholder="请输入您的姓名" />
                </u-form-item>
            </div>
            <div class="item">
                <u-form-item label="所在地区" prop="region" required :label-style="{color: '#0c3b96'}">
                    <u-input v-model="form.region" type="select" placeholder="请选择地区" @click="showRegion = true" />
                </u-form-item>
            </div>
            <div class="item" v-show="chargeShow">
                <u-form-item label="负责人" prop="chargePerson" :label-style="{color: '#0c3b96'}">
                    <span>{{form.chargePerson}}</span>
                </u-form-item>
            </div>
            <div class="item" v-show="chargeShow">
                <u-form-item label="负责人电话" prop="chargePhone" :label-style="{color: '#0c3b96'}">
                    <span>{{form.chargePhone}}</span>
                </u-form-item>
            </div>
            <div class="item">
                <u-form-item label="材料清单展示" prop="material" :label-style="{color: '#0c3b96'}" label-position="top">
                    <img style="border-radius: 3px; height: 40px; width: 50px;" class="avatar" :src="form.materialFilePath" @click="openMaterial" />
                </u-form-item>
            </div>
            <div class="item">
                <u-form-item label="上传材料" prop="fileList" required :label-style="{color: '#0c3b96'}" label-position="top">
                    <img style="border-radius: 3px; height: 50px; width: 50px;" class="avatar" src="../assets/img/photograph.png" @click="chooseMaterial" />
                </u-form-item>
                <div v-show="checkShow" style="color: #fa3534; font-size: 24rpx; margin-top: -20px;">请上传材料</div>
                <div class="file-list">
                    <div class="file-item" v-for="(item, index) in fileList" :key="index">
                        <img class="file-img" :src="item.type === 'image' ? item.url : 'https://tuanfeng.whkxzj.com/profile/static/20230109160415-file.png'" />
                        <img class="file-delete" src="https://tuanfeng.whkxzj.com/profile/static/20230109160503-delete.png" @click="remove(index)" />
                    </div>
                </div>
            </div>
            <div class="item">
                <u-form-item label="代办内容" prop="details" required :label-style="{color: '#0c3b96'}" label-position="top">
                    <u-input v-model="form.details" type="textarea" border auto-height height="150" :maxlength="1000" placeholder="请输入代办内容" />
                </u-form-item>
            </div>
            <div class="item">
                <u-form-item label="是否公开" required :label-style="{color: '#0c3b96'}">
                    <u-radio-group v-model="form.isOpen">
                        <u-radio shape="circle" :name="0" icon-size="30">是</u-radio>
                        <u-radio shape="circle" :name="1" icon-size="30">否</u-radio>
                    </u-radio-group>
                </u-form-item>
            </div>
            <!-- <div class="item">
                <u-form-item label="附件" :label-style="{color: '#0c3b96'}">
                    <div class="file-tips">上传附件不能超过20M，最多上传5个</div>
                    <div class="file-list">
                        <div class="file-item" v-for="(item, index) in fileList">
                            <img class="file-img" :src="item.type === 'image' ? item.url : 'https://tuanfeng.whkxzj.com/profile/static/20230109160415-file.png'" />
                            <div class="file-name">{{item.name}}</div>
                            <img class="file-delete" src="https://tuanfeng.whkxzj.com/profile/static/20230109160503-delete.png" @click="remove(index)" />
                        </div>
                    </div>
                    <u-button v-if="fileList.length < 5" type="primary" size="mini" ripple @click="choose">上传附件</u-button>
                </u-form-item>
            </div> -->
        </u-form>
        <u-select mode="mutil-column-auto" v-model="showRegion" :list="list" :default-value="selectRegionIndex" @confirm="confirm"></u-select>
        <u-button class="btn" type="primary" ripple shape="circle" @click="submit">提交</u-button>
    </div>
</template>
<script>
import { submitMassesAPI, getRegionList, getRegionAPI } from "../api/agency";

export default {
    data() {
        return {
            form: {
                itemId: "",
                title: "",
                open: "",
                materialFilePath: "",
                details: "",
                content: "",
                name: "",
                mail: "",
                phone: "",
                region: "",
                townId: "",
                villageId: "",
                isOpen: 0,
                chargePerson: "",
                chargePhone: "",
            },
            showRegion: false,
            show: false,
            // 地区数组
            list: [],
            // 当前选择地区
            selectRegionList: [],

            fileList: [],

            rules: {
                details: [
                    {
                        required: true,
                        message: "请输入代办内容",
                        trigger: ["blur", "change"],
                    },
                ],
                content: [
                    {
                        required: true,
                        message: "请输入代办事项",
                        trigger: ["blur", "change"],
                    },
                ],
                name: [
                    {
                        required: true,
                        message: "请输入姓名",
                        trigger: ["blur"],
                    },
                ],
                phone: [
                    {
                        required: true,
                        message: "请输入手机号",
                        trigger: ["blur"],
                    },
                    {
                        max: 11,
                        message: "请输入正确手机号",
                        trigger: ["blur", "change"],
                        validator(r, v) {
                            return v.length === 11;
                        },
                    },
                ],
                region: [
                    {
                        required: true,
                        message: "请选择地区",
                        trigger: ["blur", "change"],
                    },
                ],
            },
            checkShow: false,
            chargeShow: false,
        };
    },
    onShareAppMessage() {},
    onLoad(options) {
        let { id, title, materialFilePath, openId} = options;
        this.form.itemId = id;
        this.form.openId = openId;
        this.form.title = title;
        this.form.materialFilePath = materialFilePath;
        getRegionList().then((res) => {
            let list = [...res.data];
            this.list = this.transRegion(list);
        });
    },
    computed: {
        selectRegionIndex() {
            return this.selectRegionList.map((item) => item.extra);
        },
    },
    methods: {
        // 预览材料清单
        openMaterial() {
            wx.previewImage({
                urls: [this.form.materialFilePath]
            })
        },
        // 上传材料
        chooseMaterial() {
            wx.chooseImage({
                count: 5 - this.fileList.length,
                type: "all",
                success: (res) => {
                    const tempFilePaths = res.tempFiles;
                    let requestList = [];

                    tempFilePaths.forEach((item, index) => {
                        let promise = new Promise((resolve, reject) => {
                            wx.uploadFile({
                                url: "https://tuanfeng.whkxzj.com/file/upload",
                                filePath: tempFilePaths[index].path, //本地地址
                                name: "file",
                                success: (res) => {
                                    resolve(res);
                                },
                                fail: (err) => {
                                    reject(err);
                                },
                            });
                        });
                        requestList.push(promise);
                    });

                    wx.showLoading({
                        title: "上传中...",
                    });
                    Promise.all(requestList)
                        .then((res) => {
                            res.forEach((item) => {
                                if (item.statusCode === 200) {
                                    let data = JSON.parse(item.data) || {};
                                    if (data.code === 200) {
                                        this.fileList.push(data.data);
                                        if (this.fileList.length != 0) {
                                            this.checkShow = false;
                                        }
                                    } else {
                                        throw new Error(JSON.stringify(item));
                                    }
                                } else {
                                    throw new Error(JSON.stringify(item));
                                }
                            });
                            wx.hideLoading();
                        })
                        .catch((err) => {
                            wx.showToast({
                                title: "上传错误",
                                icon: "error",
                            });
                        });
                },
            });
        },
        transRegion(arr) {
            let list = [];
            arr.forEach((item, index) => {
                list.push({
                    value: item.id,
                    label: item.name,
                    extra: index,
                    children: item.child ? this.transRegion(item.child) : null,
                });
            });
            return list;
        },
        confirm(e) {
            this.selectRegionList = e;
            if (e.length) {
                this.form.region = "";
                e.forEach((item) => {
                    this.form.region += `${item.label} `;
                });
                this.form.townId = e[0].value;
                this.form.villageId = e[1].value;
                getRegionAPI(e[1].value).then((res) => {
                    if (res && res.data) {
                        this.form.chargePerson = res.data.chargePerson;
                        this.form.chargePhone = res.data.chargePhone;
                        this.chargeShow = true;
                    }
                })
            }
        },
        submit() {
            this.$refs.uForm.validate((valid) => {
                if (valid) {
                    if (this.fileList.length == 0) {
                        this.checkShow = true;
                        return false;
                    }
                    submitMassesAPI({
                        ...this.form,
                        fileUrls: this.fileList.map((item) => item.url),
                    }).then((res) => {
                        wx.showToast({
                            title: "提交成功",
                            icon: "success",
                        });
                        setTimeout(() => {
                            this.$u.route({ type: "back" });
                        }, 1500);
                    });
                }
            });
        },
        remove(index) {
            this.fileList.splice(index, 1);
        },
        choose() {
            wx.chooseMessageFile({
                count: 5 - this.fileList.length,
                type: "all",
                success: (res) => {
                    const tempFilePaths = res.tempFiles;
                    let requestList = [];

                    tempFilePaths.forEach((item, index) => {
                        let promise = new Promise((resolve, reject) => {
                            wx.uploadFile({
                                url: "https://tuanfeng.whkxzj.com/file/upload",
                                filePath: tempFilePaths[index].path, //本地地址
                                name: "file",
                                success: (res) => {
                                    resolve(res);
                                },
                                fail: (err) => {
                                    reject(err);
                                },
                            });
                        });
                        requestList.push(promise);
                    });

                    wx.showLoading({
                        title: "上传中...",
                    });
                    Promise.all(requestList)
                        .then((res) => {
                            res.forEach((item) => {
                                if (item.statusCode === 200) {
                                    let data = JSON.parse(item.data) || {};
                                    if (data.code === 200) {
                                        this.fileList.push(data.data);
                                    } else {
                                        throw new Error(JSON.stringify(item));
                                    }
                                } else {
                                    throw new Error(JSON.stringify(item));
                                }
                            });
                            wx.hideLoading();
                        })
                        .catch((err) => {
                            wx.showToast({
                                title: "上传错误",
                                icon: "error",
                            });
                        });
                },
            });
        },
    },
    // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
    onReady() {
        this.$refs.uForm.setRules(this.rules);
    },
};
</script>
<style scoped lang="scss">
@import "../assets/scss/common.scss";

.container {
    position: relative;
    padding: 5px 20px;
    min-height: 100vh;
    box-sizing: border-box;
    padding-bottom: 100px;
    .item {
        border-bottom: 1px solid #efefef;
        .file-tips {
            font-size: 12px;
            color: $color_secondary-text;
        }
        .file-list {
            .file-item {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin: 10px 0;
                .file-img {
                    flex: none;
                    width: 50px;
                    height: 50px;
                    margin-right: 10px;
                }
                .file-name {
                    flex: auto;
                    font-size: 12px;
                    line-height: 20px;
                    display: -webkit-box;
                    -webkit-box-orient: vertical;
                    -webkit-line-clamp: 3;
                    overflow: hidden;
                    word-break: break-all;
                }
                .file-delete {
                    flex: none;
                    width: 30px;
                    height: 30px;
                    margin-left: 10px;
                    opacity: 0.8;
                }
            }
        }
    }
    .btn {
        position: absolute;
        left: 30px;
        right: 30px;
        bottom: 50px;
    }
}
</style>
